package org.lyg.controller;

import org.apache.shiro.SecurityUtils;
import org.lyg.domain.Blog;
import org.lyg.domain.Tag;
import org.lyg.domain.User;
import org.lyg.service.IBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    IBlogService blogService;

    @RequestMapping("/edit")
    public String edit(ModelMap modelMap, HttpServletRequest req) {
        return edit(-1, modelMap, req);
    }

    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id") int id, ModelMap modelMap) {
        Blog blog = blogService.getBlogById(id);
        modelMap.addAttribute("blog", blog);
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        modelMap.addAttribute("userSelf", user);
        return "blogdetail";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable int id, ModelMap modelMap, HttpServletRequest req) {
        Blog blog = blogService.getBlogById(id);
        if (blog != null) {
            req.getSession().setAttribute("blog-" + blog.getId(), blog);
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        modelMap.addAttribute("userSelf",user);
        modelMap.addAttribute("blog", blog);
        return "editblog";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Blog blog, ModelMap modelMap, HttpServletRequest req) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        blog.setAuthor(user);
        blog.setTag(new Tag(1));
        blog.setEditTime(new Date());
        Blog b = (Blog) req.getSession().getAttribute("blog-" + blog.getId());
        req.getSession().removeAttribute("blog-" + blog.getId());
        if (b == null) {
            blog.setCreateTime(new Date());
        }else if(b.getAuthor().getId()!=user.getId()){
            //文章不属于当前用户
            modelMap.addAttribute("blog", blog);
            modelMap.addAttribute("msg", "保存出错！");
            return "editblog";
        }
        if (blogService.save(blog)) {
            return "redirect:/user/center/" + user.getName();
        } else {
            modelMap.addAttribute("blog", blog);
            modelMap.addAttribute("msg", "保存失败！");
            return "editblog";
        }
    }
}
